package com.andreamerla.petslife.adapter;

import android.content.Context;
import android.location.Location;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.andreamerla.petslife.R;
import com.andreamerla.petslife.manager.GpsTracker;
import com.andreamerla.petslife.model.Place;
import com.andreamerla.petslife.util.Utils;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: a.merla
 * Date: 22/07/13
 * Time: 10.51
 */
public class PlaceAdapter extends ArrayAdapter<Place> {
    private Context context;
    private GpsTracker gpsTracker;

    public PlaceAdapter(Context context, List<Place> placeList) {
        super(context, R.layout.place_adapter_layout, placeList);

        this.context = context;
        this.gpsTracker = GpsTracker.getInstance();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.place_adapter_layout, parent, false);
        }

        Place place = getItem(position);

        // Place name
        TextView tvPlaceName = (TextView) convertView.findViewById(R.id.tv_place_name);
        tvPlaceName.setText(place.name);

        // Place address
        TextView tvPlaceAddress = (TextView) convertView.findViewById(R.id.tv_place_address);
        tvPlaceAddress.setText(place.vicinity);

        // Place distance
        Location location = gpsTracker.getLocation();
        if (location != null) {
            float[] distanceResults = new float[1];
            Location.distanceBetween(location.getLatitude(), location.getLongitude(), place.geometry.location.lat, place.geometry.location.lng, distanceResults);
            float distance = Utils.round(distanceResults[0] / 1000f, 1);
            Log.d(Utils.getLogTag(this.getClass()), "Distance between (" + location.getLatitude() + "," + location.getLongitude() + ")" +
                    " and (" + place.geometry.location.lat + "," + place.geometry.location.lng + ") is " + distance + "km");

            TextView tvPlaceDistance = (TextView) convertView.findViewById(R.id.tv_place_distance);
            tvPlaceDistance.setText(Float.toString(distance));
        }

        return convertView;
    }
}
